import Vue from 'vue'
import Vuex from 'vuex'
import { addRoutes } from '@/permission'
import { getMenu, getToken, getUser, removeUserInfo, setUserInfo } from '@/utils/auth'
import { login, logout, register } from '@/api/login'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: getToken(),
    user: getUser(),
    menu: getMenu()
  },
  getters: {
    menu: state => state.menu,
    name: state => state.user && state.user.nickName,
    userId: state => state.user && state.user.id
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USER: (state, user) => {
      state.user = user
    },
    SET_MENU: (state, menu) => {
      state.menu = menu
      addRoutes(menu)
    }
  },
  actions: {
    logout({ state }) {
      return new Promise((resolve, reject) => {
        if (!state.token) {
          reject({ message: '无效的token，退出失败！', success: false })
          return
        }
        logout().then(({ success, message }) => {
          if (!success) {
            reject({ message })
            return
          }
          resolve()
          removeUserInfo()
        }).catch((e) => {
          reject(e)
        })
      })
    },
    login({ commit }, data) {
      return new Promise((resolve, reject) => {
        login(data).then(({ success, data, message }) => {
          if (success) {
            commit('SET_TOKEN', data.token)
            commit('SET_USER', data.user)
            commit('SET_MENU', data.menus)
            setUserInfo(data)
            resolve(data)
          } else {
            reject(message)
          }
        })
      })
    },
    removeUserInfo({ commit }) {
      commit('SET_USER_INFO', removeUserInfo())
    },
    register(store, data) {
      return new Promise((resolve, reject) => {
        register(data).then(({ success, data, message }) => {
          if (success) {
            setUserInfo(data)
            resolve(data)
          } else {
            reject(message)
          }
        })
      })
    }
  }
})
